#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>

#define MAXLINE 1024

int main() {
    // 创建socket对象
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("socket creation failed");
        return 1;
    }

    // 创建网络通信对象
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(1324);
    addr.sin_addr.s_addr = INADDR_ANY;

    // 绑定socket对象与通信链接
    if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("bind failed");
        return 1;
    }

    // 监听连接
    listen(sockfd, 5);

    // 接受连接
    struct sockaddr_in cli;
    socklen_t len = sizeof(cli);
    int newsockfd = accept(sockfd, (struct sockaddr *) &cli, &len);
    if (newsockfd < 0) {
        perror("ERROR on accept");
        exit(1);
    }

    while (1) {
        char buf[MAXLINE];
        ssize_t n = recv(newsockfd, buf, MAXLINE, 0);
        if (n < 0) {
            perror("接收失败");
            break;
        }
        buf[n] = '\0';
        printf("接收到的客户端消息：%s\n", buf);

        char reply[] = "Message received";
        if (send(newsockfd, reply, strlen(reply), 0) < 0) {
            perror("发送失败");
            break;
        }
    }

    close(newsockfd);
    close(sockfd);

    return 0;
}
